<template>
  <div class="login-container">
    <el-form ref="loginFormRef" :model="loginForm" class="login-form register-info"
             :rules="activeName==='tab1'?tab1LoginRules:tab2LoginRules">
      <h3 class="title">LINQ-CAR</h3>
      <el-tabs v-model="activeName" :stretch="true" @tab-click="handleTabClick">
        <!--   登录     -->
        <el-tab-pane label="登录" name="tab1">
          <el-form-item prop="phone">
            <el-input v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号" minlength="11"
                      maxlength="11"/>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" minlength="5"
                      maxlength="20" @keyup.enter.native="handleLogin"/>
          </el-form-item>
          <el-form-item prop="code">
            <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
                      @keyup.enter.native="handleLogin"/>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode" class="login-code-img" alt="暂无"/>
            </div>
          </el-form-item>
        </el-tab-pane>

        <!--注册-->
        <el-tab-pane label="注册" name="tab2">
          <el-tooltip class="item" effect="dark" content="手机号是唯一的哦~" placement="top-start">
            <el-form-item prop="phone">
              <el-input v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号" minlength="11"
                        maxlength="11" @keyup.enter.native="handleLogin"/>
            </el-form-item>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="密码要记住哦~" placement="top-start">
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
                        minlength="5"
                        maxlength="20" @keyup.enter.native="handleLogin"/>
            </el-form-item>
          </el-tooltip>
          <el-form-item prop="county">
            <el-cascader filterable size="mini" :options="options" placeholder="所在城市" v-model="selectedOptions"
                         @change="handleCityChange"/>
          </el-form-item>
          <el-row>
            <el-col>
              <el-form-item prop="code">
                <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
                          @keyup.enter.native="handleLogin"/>
                <div class="login-code">
                  <img :src="codeUrl" @click="getCode" class="login-code-img" alt=""/>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <!--记住\忘记密码-->
      <el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;">记住密码</el-checkbox>
        <a class="forget-password" style="float: right;" @click.prevent="toForgetPwd">
          忘记密码
        </a>
      </el-form-item>
      <el-form-item style="width:100%;" v-if="activeName === 'tab1'">
        <el-button :loading="loginBtnLoading" size="large" type="primary" style="width:100%;"
                   @click.native.prevent="handleLogin">
          <span v-if="!loginBtnLoading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
      <el-form-item style="width:100%;" v-else>
        <el-button :loading="loginBtnLoading" size="large" type="primary" style="width:100%;"
                   @click.native.prevent="handleLogin">
          <span v-if="!loginBtnLoading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { reactive, toRefs, onMounted, ref } from 'vue'
import { encrypt } from '../utils/jsencrypt'
import loginApi from '../api/login.js'
import { setStore, removeStore, getStore } from '../utils/storage.js'
import { regionDataPlus, CodeToText } from 'element-china-area-data'
import { ElMessage } from 'element-plus'

export default {
  name: 'Login',
  setup () {
    const store = useStore()
    const router = useRouter()
    console.log(store.getters)
    // 绑定dom元素
    const loginFormRef = ref(null)
    const state = reactive({
      // 市区级联
      options: regionDataPlus,
      selectedOptions: [],
      // 登录使用
      loginForm: {
        phone: '18061877017',
        password: '111222',
        uuid: undefined,
        code: undefined,
        province: '',
        city: '',
        county: '',
        rememberMe: false
      },
      // 图片验证码地址
      codeUrl: '',
      // 激活tab
      activeName: 'tab1',
      // 按钮加载状态
      loginBtnLoading: false,
      // 账号密码tab 校验
      tab1LoginRules: {
        phone: [
          { require: true, trigger: 'change', message: '手机号不合法', pattern: /^1[34578]\d{9}$/ },
          { required: true, trigger: 'change', message: '手机号不能为空' }
        ],
        password: [
          { required: true, trigger: 'change', message: '密码不能为空' }
        ],
        code: [{ required: true, trigger: 'change', message: '验证码不能为空' }]
      },
      // 注册账号tab校验
      tab2LoginRules: {
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'change' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'change' }
        ],
        code: [{ required: true, trigger: 'change', message: '验证码不能为空' }],
        // county: [
        //   { required: true, message: '所在城市不能为空', trigger: 'change' }
        // ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'change' }
        ],
        gender: [
          { required: true, message: '客户性别不能为空', trigger: 'change' }
        ],
      },
    })

    //-------------------- methdo start
    // 获取图片验证码地址
    const getCode = () => {
      loginApi.getCodeImg().then(res => {
        const { img, uuid } = res.data
        state.codeUrl = img
        state.loginForm.uuid = uuid
      })
    }
    // tab切换处理时候 会清空前面一个tab的记录
    const handleTabClick = () => {
      // 表单重置
      loginFormRef.value.resetFields()
      state.selectedOptions = []
      // 验证码变动
      getCode()
    }
    // 处理登录
    const handleLogin = () => {
      if (!loginFormRef.value) return
      loginFormRef.value.validate(valid => {
        console.log(valid)
        if (valid) {
          state.loginBtnLoading = true
          setTimeout(() => {
            state.loginBtnLoading = false
            getCode()
          }, 2000)
          // 切换到tab1 登录
          if (state.activeName === 'tab1') {
            console.log('登录操作')
            // 如果需要记住密码 就缓存到cookie
            if (state.loginForm.rememberMe) {
              setStore('phone', state.loginForm.phone)
              setStore('password', encrypt(state.loginForm.password))
              setStore('rememberMe', state.loginForm.rememberMe)
            } else {
              removeStore('phone')
              removeStore('password')
              removeStore('rememberMe')
            }
            // 构造登录信息
            const loginInfo = {
              phone: state.loginForm.phone,
              password: state.loginForm.password,
              uuid: state.loginForm.uuid,
              code: state.loginForm.code
            }
            store.dispatch('Login', loginInfo).then(() => {
              loginFormRef.value.resetFields()
              // path不能和params一起使用，否则params将无效。需要用name来指定页面。
              router.push({
                path: '/'
              })
            }).catch(() => {
            })
          } else {
            // 注册逻辑 tab2
            console.log('注册操作')
            // 构造注册信息
            const registerInfo = {
              province: state.loginForm.province,
              city: state.loginForm.city,
              county: state.loginForm.county,
              phone: state.loginForm.phone,
              password: state.loginForm.password,
              uuid: state.loginForm.uuid,
              code: state.loginForm.code
            }
            loginApi.register(registerInfo).then(res => {
              loginFormRef.value.resetFields()
              state.selectedOptions = []
              state.activeName = 'tab1'
              ElMessage.success('注册成功,去登录吧~')
            })

          }
        }
      })
    }
    // 级联选择的值
    const handleCityChange = (arr) => {
      let province = CodeToText[arr[0]]
      let city = CodeToText[arr[1]]
      let county = CodeToText[arr[2]]
      state.loginForm.province = province
      state.loginForm.city = city
      state.loginForm.county = county
    }
    // 忘记密码
    const toForgetPwd = () => {
      ElMessage.warning('请联系管理员')
    }
    //-------------------- method end

    //---------------------钩子
    // 调用图片验证码
    onMounted(() => {
      getCode()
    })

    return {
      ...toRefs(state),
      loginFormRef,
      handleTabClick,
      toForgetPwd,
      getCode,
      handleLogin,
      handleCityChange
    }
  },
}
</script>
<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-bg.jpg");
  background-size: cover;
}

.title {
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 450px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.getCaptcha {
  display: block;
  width: 100%;
  height: 40px;
}

.forget-password {
  font-size: 14px;
  color: rgb(29, 142, 250);
}

.forget-password:hover {
  color: rgb(46, 195, 251);
}

.other-login {
  text-align: left;
  margin-top: 24px;
  line-height: 22px;

  .item-icon {
    font-size: 24px;
    color: rgba(0, 0, 0, 0.2);
    margin-left: 16px;
    vertical-align: middle;
    cursor: pointer;
    transition: color 0.3s;

    &:hover {
      color: #1890ff;
    }
  }

  .register {
    float: right;
    color: rgb(29, 142, 250);
  }

  .register:hover {
    color: rgb(46, 195, 251);
  }
}

.register-info::v-deep .el-cascader.el-cascader--mini {
  width: 450px;
}

</style>

